package pos.utils;

/**
 * 引自"SEGobang"项目的XML配置文件操作类
 * @author 彭涛
 */
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class XMLConfig {
    public XMLConfig() {
        file = PathRes.getPath("Config.XML");
        init();
    }

    public XMLConfig(String filepath) {
        file = filepath;
        init();
    }

    private void init() {
        try{
            File xmlFile = new File(file);
            DocumentBuilderFactory factory = 
                    DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(xmlFile);
        }
        catch(Exception e){
            System.out.println(e);
        }
    }

    public String getData(String tagName) {
        NodeList nodeList = doc.getElementsByTagName(tagName);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node child = nodeList.item(i);
            if (child instanceof Element) {
                Element childElement = (Element) child;
                Text textNode = (Text) childElement.getFirstChild();
                return textNode.getData().trim();
            }
        }
        return null;
    }

    public void setData(String tagName, String text) {
        doc.getElementsByTagName(tagName).
                item(0).getFirstChild().setNodeValue(text);
        updateFile(doc,file);
    }

    public void appendNode(String tagName, String text) {
        Element element =doc.createElement(tagName);
        element.setTextContent(text);
        Element root=doc.getDocumentElement();
        root.appendChild(element);
        updateFile(doc,file);
    }
    
    public void removeNode(String tagName){
        NodeList nodeList = doc.getElementsByTagName(tagName);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node child = nodeList.item(i);
            if (child instanceof Element) {
                doc.getDocumentElement().removeChild(child);
            }
        }
        updateFile(doc,file);
    }

    private void updateFile(Document document, String filename) {
        try {
            TransformerFactory tFactory = 
                    TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
          
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new File(filename));
            transformer.transform(source, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String file;
    private Document doc;
}
